package com.snow.student;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

public class StudentServer {
    private Server server;

    private void start() throws IOException {
        this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start();

        System.out.println("server started!");

        //增加一个线程，当正常关闭jvm时关闭此服务器；当强行关闭本线程，则不会执行。
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("关闭jvm");
            StudentServer.this.stop();
        }));
    }

    private  void stop(){
        if (null != this.server){
            this.server.shutdown();
        }
    }

    //此方法是为了阻塞服务器，使其一直等待服务器的链接
    private void awaitTermination() throws InterruptedException{
        if (null != this.server){
            this.server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        StudentServer server = new StudentServer();

        server.start();
        server.awaitTermination();
    }
}
